package cn.stylefeng.guns.sys.modular.system.service;


import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.GzhConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskStatusParam;
import cn.stylefeng.guns.sys.modular.system.service.impl.ProjectServiceImpl;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class MouldBoardMsgService extends ServiceImpl<MouldBoardMsgMapper, MouldBoardMsg> {

    private final static Logger logger = LoggerFactory.getLogger(MouldBoardMsgService.class);
    @Resource
    private ProjectServiceImpl projectServiceImpl;
    @Resource
    private TaskStatusService taskStatusService;
    @Resource
    private TaskStatusMapper taskStatusMapper;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private TaskFlowService taskFlowService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private UserService userService;
    @Resource
    private BtyWxMapper btyWxMapper;
    @Resource
    private GcgMsgMapper gcgMsgMapper;
    @Resource
    private GzhConfig gzhConfig;
    @Resource
    private MouldBoardMsgService mouldBoardMsgService;

    // 跳转URL
    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
    private String type = "&response_type=code";
    private String scope = "&scope=snsapi_userinfo";
    private String state = "&state=STATE#wechat_redirect";

    /**
     * 添加内容
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addMouldBoardMsg(List<MouldBoardMsg> mouldBoardMsgs) throws ParseException {
        Integer mouldId = mouldBoardMsgs.get(0).getMouldId();
        Integer proId = mouldBoardMsgs.get(0).getProId();
//        TaskStatus taskStatus=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",proId)
//        .eq("task_id",6).eq("status",0));
//        if(ToolUtil.isNotEmpty(taskStatus)){
//            TaskStatusParam param=new TaskStatusParam();
//            param.setProId(proId);
//            param.setTaskId(6);
//            param.setStatus(0);
//            taskStatusMapper.deletes(param);
//        }

        int taskid = 0;
        int status = 0;
        String taskname="";
        if(mouldId==36){
            taskid=3;
            status = 1;
        }else if(mouldId==38){
            taskid=2;
            status = 1;
        }//网上建店位置对应的taskid36
        else if(mouldId==34){
            taskid=36;
            status = 0;
        }
        //线上套餐对应的taskid37
        else if(mouldId==35){
            taskid=37;
            status = 0;
        }
        //排队机对应的taskid38
        else if(mouldId==37){
            taskid=38;
            status = 0;
        }
        //现场踏勘对应的taskid30
        else if(mouldId==39){
            taskid=30;
            status = 1;
        }
        //查询是否重复提交
        taskname=taskMapper.selectById(taskid).getName();
        TaskStatus ts = new TaskStatus(proId,taskid,status,"",taskname);
        TaskStatusParam tsparam=new TaskStatusParam(proId,taskid,status,"",taskname,LoginContextHolder.getContext().getUserId());
        boolean exist = taskStatusService.isExist(ts);
        if(exist){
            return ResponseData.error("已提交，不能重复提交");
        }
        int delete = this.delete(mouldBoardMsgs.get(0).getProId(), mouldBoardMsgs.get(0).getMouldId());


        String con = null;

        boolean save = false;
        for (MouldBoardMsg msg : mouldBoardMsgs
        ) {
            msg.setMouldId(mouldId);
            msg.setProId(proId);
            save = this.save(msg);

            //获取现场踏勘图片路径
            if (ToolUtil.isNotEmpty(msg.getPinCode()) && msg.getPinCode().equals("wwztimg")){
                con = msg.getData();
            }
        }

        //现场踏勘
        if (taskid == 30){
            ts = new TaskStatus(proId,taskid,status,con,taskname);
        }else {
            ts = new TaskStatus(proId,taskid,status,"",taskname);
        }



        //现场踏勘
        if (taskid == 30){
            //当前日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String date = df.format(new Date());

            //当前日期+7
            String seven = DateUtil.addDate(date, 7);
            //当前日期+10
            String ten = DateUtil.addDate(date, 10);
            String con1 = seven + "~" + ten;

            //出图日期
            TaskStatus status1 = new TaskStatus();
            status1.setTaskId(31);
            status1.setProId(proId);
            status1.setStatus(0);
            status1.setTaskName("出图日期");
            status1.setContent(con1);
            status1.setCreateId(LoginContextHolder.getContext().getUserId());

            boolean d = taskStatusService.save(status1);

            //流程明细表
            TaskFlow taskFlow = new TaskFlow();
            taskFlow.setProId(proId);
            taskFlow.setTaskId(31);
            taskFlow.setStatus(0);//1提交；2审核未通过；3审核通过
            taskFlow.setTaskName("出图日期");
            taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
            taskFlow.setCreateTime(new Date());

            boolean e = taskFlowService.save(taskFlow);

        }
        boolean b = false;
        int existnum = taskStatusService.selectStau(tsparam);
        if(existnum>0){
            int i = taskStatusService.updateAuditSt(tsparam);
            b=(i>0?true:false);
        }else{
            //
           b=taskStatusService.save(ts);
           //工程条件保存之后删除工程驳回状态
            taskStatusMapper.delete(new QueryWrapper<TaskStatus>().eq("pro_id",proId).eq("task_id",5).eq("status",0));

        }


        TaskFlow flow=new TaskFlow();
        flow.setProId(proId);
        flow.setTaskId(taskid);
        flow.setStatus(status);
        flow.setTaskName(taskname);
        flow.setCreateUser(LoginContextHolder.getContext().getUserId());
        boolean c=taskFlowService.save(flow);

        //插入下个节点
        taskStatusService.insertNextNode(new TaskStatusParam(ts.getProId(),ts.getTaskId(),ts.getCreateId()));
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        List<Long> roleList = currentUser.getRoleList();

        //微信推送 // TODO: 2022-07-26 需要一个判断是开发区域经理的标志
        String qyjlPhone="";
        List<MouldBoardMsg>list=mouldBoardMsgService.list(new QueryWrapper<MouldBoardMsg>().eq("pro_id",proId).eq("pin_code","developmentManagerPhone"));
        if(ToolUtil.isNotEmpty(list)&&list.size()>0){
            qyjlPhone=list.get(0).getData();
            Project project=projectServiceImpl.getById(proId);
            if(ToolUtil.isNotEmpty(project)&&ToolUtil.isNotEmpty(qyjlPhone)){
                project.setKfqyjl(qyjlPhone);
                projectServiceImpl.updateById(project);
            }
        }

        if(save && b && c){
            //商务条件
            if(mouldId==36){
                if(ToolUtil.isNotEmpty(qyjlPhone)){
                    ts.setStatus(BusConst.AUDIT_TODO);
                    projectServiceImpl.pushMsg2KFQYJL(proId, ts,qyjlPhone);
                }else {
                    ts.setStatus(BusConst.AUDIT_TODO);
                    projectServiceImpl.pushMsg2KFZJ(proId, ts);
                }
//                projectServiceImpl.pushMsg2GCZJ(proId, ts);
                //工程条件
            }else if (mouldId == 38){
                ts.setStatus(BusConst.AUDIT_TODO);
//                projectServiceImpl.pushMsg2KFZJ(proId, ts);
                projectServiceImpl.pushMsg2GCZJ(proId, ts);
            }
        }
        String dm = taskMapper.selectDm(proId);//店名

        //网上建店/线上套餐/排队机
        if (taskid == 36 || taskid == 37 || taskid == 38){

            String data = dm + ",督导已提交" + taskname + "!";

            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, taskname, taskname, DateUtil.getNow(), data);

            //网上建店负责人
            Long role = 1307580056085250050L;//网上建店负责人
            List<String> openidlist = userService.listOpenidsByRole(role);

            if (ToolUtil.isNotEmpty(openidlist)){
                logger.info("=========网上建店负责人:" + openidlist + "========");

                String[] openids = openidlist.toArray(new String[openidlist.size()]);

                //推送网上建店负责人
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("========推送网上建店负责人消息==========");
            }

            //现场踏勘
        }else if (taskid == 30){
            //工程设计
            Long gcsj = 1373822382028705794L;
            List<String> openidlist = userService.listOpenidsByRole(gcsj);

            if (ToolUtil.isNotEmpty(openidlist)){
                logger.info("=========工程设计:" + openidlist + "========");

                //工程设计id
                List<User> user1 = btyWxMapper.getUser(openidlist);

                if (ToolUtil.isNotEmpty(user1)) {
                    for (User user : user1) {

                        String[] openids = new String[]{user.getOpenid()};

                        //推送工程设计消息
                        String data = dm + "现场踏勘信息已提交，请及时完成设计图！";
                        logger.info("==========现场踏勘信息已提交========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, "确认出图日期", "出图日期", DateUtil.getNow(), data);

                        //出图日期url
                        String syUrl = BusConst.WGURL + "&proId=" + proId + "&taskId=31" + "&userId=" + user.getUserId();
                        String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                        //推送工程设计消息
                        weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                        logger.info("=======推送工程设计消息==========");


                        //消息表中新增出图日期消息
                        GcgMsg gcgMsg = new GcgMsg();
                        gcgMsg.setBusinessId(proId);//业务id
                        gcgMsg.setBusinessType("工程");//业务类型
                        gcgMsg.setBusinessName(dm);//业务名称
                        gcgMsg.setTaskId(31);//任务id
                        gcgMsg.setMsgType("填写出图日期提醒");//消息类型
                        gcgMsg.setMessage(data);//消息内容
                        gcgMsg.setPath(url);//跳转路径
                        gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                        gcgMsg.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                        gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                        gcgMsg.setCreateTime(new Date());//创建时间

                        //消息表新增出图日期消息
                        gcgMsgMapper.insert(gcgMsg);
                    }
                }
            }

        }
        return ResponseData.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseData addMouldBoardMsgAdmin(List<MouldBoardMsg> mouldBoardMsgs) {
        Integer mouldId = mouldBoardMsgs.get(0).getMouldId();
        Integer proId = mouldBoardMsgs.get(0).getProId();

        int taskid = 0;
        int status = 0;
        String taskname="";
        if(mouldId==36){
            taskid=3;
            status = 1;
        }else if(mouldId==38){
            taskid=2;
            status = 1;
        }//网上建店位置对应的taskid36
        else if(mouldId==34){
            taskid=36;
            status = 0;
        }
        //线上套餐对应的taskid37
        else if(mouldId==35){
            taskid=37;
            status = 0;
        }
        //排队机对应的taskid38
        else if(mouldId==37){
            taskid=38;
            status = 0;
        }
        //现场踏勘对应的taskid30
        else if(mouldId==39){
            taskid=30;
            status = 1;
        }
        //查询是否重复提交
        taskname=taskMapper.selectById(taskid).getName();
        TaskStatus ts = new TaskStatus(proId,taskid,status,"",taskname);
        boolean exist = taskStatusService.isExist(ts);
        if(exist){
            return ResponseData.error("已提交，不能重复提交");
        }

        int delete = this.delete(mouldBoardMsgs.get(0).getProId(), mouldBoardMsgs.get(0).getMouldId());

        boolean save = false;
        for (MouldBoardMsg msg : mouldBoardMsgs
        ) {
            msg.setMouldId(mouldId);
            msg.setProId(proId);
            save = this.save(msg);
        }

        boolean b = taskStatusService.save(ts);
        TaskFlow flow=new TaskFlow();
        flow.setProId(proId);
        flow.setTaskId(taskid);
        flow.setStatus(status);
        flow.setTaskName(taskname);
        flow.setCreateUser(LoginContextHolder.getContext().getUserId());
        boolean c=taskFlowService.save(flow);

        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        List<Long> roleList = currentUser.getRoleList();

        //微信推送
        if(save&&b&&c){
            //商务条件
            if(mouldId==36){
                ts.setStatus(BusConst.AUDIT_TODO);
                projectServiceImpl.pushMsg2KFZJadmin(proId, ts);

//                projectServiceImpl.pushMsg2GCZJ(proId, ts);
                //如果工程管理员则推送给开发人员消息
                projectServiceImpl.pushMsg2KFRYadmin(proId,ts.getTaskId(),ts);
                //工程条件
            }else if (mouldId == 38){
                ts.setStatus(BusConst.AUDIT_TODO);
//                projectServiceImpl.pushMsg2KFZJ(proId, ts);
                projectServiceImpl.pushMsg2GCZJadmin(proId, ts);
                //如果是工程管理员则推送给开发人员消息
                projectServiceImpl.pushMsg2KFRYadmin(proId,ts.getTaskId(),ts);
            }
        }
        //网上建店/线上套餐/排队机
        if (taskid == 36 || taskid == 37 || taskid == 38){

            String dm = taskMapper.selectDm(proId);//店名
            String data = dm + ",督导已提交" + taskname + "!";

            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, null, taskname, taskname, DateUtil.getNow(), data);

            //网上建店负责人
            Long role = 1307580056085250050L;//网上建店负责人
            List<String> openidlist = userService.listOpenidsByRole(role);

            if (ToolUtil.isNotEmpty(openidlist)){
                logger.info("=========网上建店负责人:" + openidlist + "========");

                String[] openids = openidlist.toArray(new String[openidlist.size()]);

                //推送网上建店负责人
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("========推送网上建店负责人消息==========");
            }

        }
        return ResponseData.success();
    }

    /**
     * 添加内容
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int delete(Integer proId, Integer moudelId) {
        return this.baseMapper.deleteMoudelMsg(proId,moudelId);
    }


    public LayuiPageInfo listDataShangwu(MouldBoardMsg param){
        Page page = LayuiPageFactory.defaultPage();
        IPage list = baseMapper.listDataShangwu(page,param);
        return LayuiPageFactory.createPageInfo(list);
    }

    /**
     * 工程条件查询
     * @param param
     * @return
     */
    public LayuiPageInfo listDataGongcheng(MouldBoardMsg param) {
        Page page = LayuiPageFactory.defaultPage();
        IPage list = baseMapper.listDataGongcheng(page,param);
        return LayuiPageFactory.createPageInfo(list);
    }
}
